package com.lxt.filemanager.controller;

import com.lxt.filemanager.entity.DFSAddress;
import com.lxt.filemanager.entity.TblFile;
import com.lxt.filemanager.service.TblFileService;
import org.csource.common.MyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.swing.plaf.multi.MultiInternalFrameUI;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
@Controller
public class FileController {
    @Resource
    private TblFileService tblFileService;

    @GetMapping("/")
    public String defaultPage() {
        return "redirect:/list";
    }

    /**
     * 查询数据库内所有文件
     * @return
     */
    @GetMapping("/list")
    public String list(Model model){
        List<TblFile> list = tblFileService.list();
        model.addAttribute("files",list);
        return "index";
    }

    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public String toUpload(MultipartFile file,Model model) throws IOException, MyException {
        String fileInfo = file.getOriginalFilename();
        int splitPoint = fileInfo.lastIndexOf(".");
        TblFile tblFile = new TblFile();
        tblFile.setFileName(fileInfo.substring(0,splitPoint));
        tblFile.setExtName(fileInfo.substring(splitPoint+1));
        tblFile.setFileSize(file.getSize());
        byte[] fileData = file.getBytes();
        tblFileService.upLoad(tblFile,fileData);
        return "redirect:/list";
    }

    /**
     * 下载文件
     */
    @GetMapping("/download/{id}")
    public void downloadFile(@PathVariable("id") Integer id, HttpServletResponse response) throws IOException, MyException {
        DFSAddress download = tblFileService.download(id);
        response.setHeader("content-disposition","attachment;fileName="+download.getFileName());
        response.getOutputStream().write(download.getData());
    }

    /**
     * 查看文件
     */
    @GetMapping("/show/{id}")
    public void showFile(@PathVariable("id") Integer id, HttpServletResponse response) throws IOException, MyException {
        DFSAddress download = tblFileService.download(id);
        response.getOutputStream().write(download.getData());
    }

    /**
     * 删除文件
     */
    @GetMapping("/delete/{id}")
    public String deleteFile(@PathVariable("id") Integer id) throws IOException, MyException {
        boolean delete = tblFileService.delete(id);
        return "redirect:/list";
    }


}
